<template>
  <div class="home">
    <el-container>
      <el-header>
        <nav-bar></nav-bar>
      </el-header>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="article-list">
              <el-input
                v-model="searchQuery"
                placeholder="搜索文章..."
                prefix-icon="Search"
                clearable
                @input="handleSearch"
              />
              <!-- 修正：将注释移到标签外部 -->
              <article-card
                v-for="article in articles"
                :key="article.id"
                :article="article"
                @click="viewArticle(article._id)"
              ></article-card>
              <div v-if="articles.length === 0" class="empty-state">
                <el-empty description="暂无文章" v-if="!loading"></el-empty>
                <div v-else>
                  <el-skeleton :rows="3" animated />
                  <el-divider />
                  <el-skeleton :rows="3" animated />
                </div>
              </div>
            </div>
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                :disabled="loading"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="sidebar">
              <el-card class="profile-card" v-if="currentUser">
                <template #header>
                  <div class="card-header">
                    <span>个人信息</span>
                  </div>
                </template>
                <div class="profile-content">
                  <h3>{{ currentUser.username }}</h3>
                  <p>{{ currentUser.email }}</p>
                  <el-button type="primary" @click="$router.push('/write')">写文章</el-button>
                </div>
              </el-card>
              <el-card class="tags-card">
                <template #header>
                  <div class="card-header">
                    <span>热门标签</span>
                  </div>
                </template>
                <div class="tags-content">
                  <el-tag
                    v-for="tag in tags"
                    :key="tag"
                    :type="getTagType(tag)"
                    class="mx-1"
                    effect="plain"
                    @click="filterByTag(tag)"
                    :class="{ active: selectedTag === tag }"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </el-card>
            </div>
          </el-col>
        </el-row>
      </el-main>
      <el-footer>
        <footer-component></footer-component>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'
import NavBar from '../components/NavBar.vue'
import ArticleCard from '../components/ArticleCard.vue'
import FooterComponent from '../components/FooterComponent.vue'

export default {
  name: 'Home',
  components: {
    NavBar,
    ArticleCard,
    FooterComponent
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const allArticles = ref([])  // 存储所有文章
    const articles = ref([])     // 当前页显示的文章
    const loading = ref(false)
    const selectedTag = ref('')
    const tags = ref([
      'Vue.js',
      'React',
      'Node.js',
      'Python',
      'JavaScript',
      '前端开发',
      '后端开发',
      '数据库'
    ])
    const currentPage = ref(1)
    const pageSize = ref(parseInt(localStorage.getItem('preferred_page_size')) || 10)
    const total = ref(0)
    const searchQuery = ref('')

    const currentUser = computed(() => store.getters.currentUser)

    // 根据标签和搜索条件过滤文章
    const filteredArticles = computed(() => {
      let result = [...allArticles.value]
      
      // 标签过滤
      if (selectedTag.value) {
        result = result.filter(article => 
          article.tags && article.tags.includes(selectedTag.value)
        )
      }
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(article => 
          article.title.toLowerCase().includes(query) ||
          article.content.toLowerCase().includes(query)
        )
      }
      
      // 更新总数
      total.value = result.length
      
      // 分页处理
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })

    // 获取所有文章
    const fetchAllArticles = async () => {
      if (loading.value) return
      loading.value = true
      try {
        const response = await store.dispatch('fetchArticles')
        if (response && Array.isArray(response.articles)) {
          allArticles.value = response.articles
          total.value = response.articles.length
        } else {
          console.warn('Invalid response format:', response)
          allArticles.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取文章列表失败：', error)
        allArticles.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      localStorage.setItem('preferred_page_size', newSize)
      currentPage.value = 1
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    const filterByTag = (tag) => {
      selectedTag.value = selectedTag.value === tag ? '' : tag
      currentPage.value = 1  // 重置到第一页
    }

    const handleSearch = debounce(() => {
      currentPage.value = 1  // 重置到第一页
    }, 300)

    const getTagType = (tag) => {
      const types = ['primary', 'success', 'info', 'warning', 'danger']
      const index = tag.length % types.length
      return types[index]
    }

    const viewArticle = (id) => {
      console.log('点击的文章ID:', id); // 添加日志验证ID是否存在
      if (id) {
        router.push(`/article/${id}`)
      } else {
        console.error('文章ID为空，无法跳转');
      }
    }

    // 初始化加载
    onMounted(() => {
      fetchAllArticles()
    })

    return {
      articles: filteredArticles,
      currentUser,
      tags,
      loading,
      selectedTag,
      getTagType,
      viewArticle,
      filterByTag,
      currentPage,
      pageSize,
      total,
      handleSizeChange,
      handleCurrentChange,
      searchQuery,
      handleSearch
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto;
}

.el-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.sidebar {
  position: sticky;
  top: 20px;
}

.profile-card,
.tags-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  text-align: center;
}

.profile-content h3 {
  margin: 10px 0;
  color: #303133;
}

.profile-content p {
  color: #606266;
  margin-bottom: 15px;
}

.tags-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.mx-1 {
  margin: 0 4px;
  cursor: pointer;
}

.empty-state {
  padding: 40px 0;
}

.tags-content .el-tag {
  margin: 5px;
  cursor: pointer;
}

.tags-content .el-tag.active {
  transform: scale(1.1);
  font-weight: bold;
}

.tags-content .el-tag:hover {
  transform: scale(1.1);
}

.article-list {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 10px 0;
}

.el-pagination {
  --el-pagination-font-size: 14px;
  --el-pagination-bg-color: #fff;
  --el-pagination-hover-color: var(--el-color-primary);
}

@media screen and (max-width: 768px) {
  .el-main {
    padding: 10px;
  }

  .el-row {
    margin: 0 !important;
  }

  .el-col {
    padding: 0 !important;
  }

  .pagination-container {
    margin-top: 10px;
  }
}
</style>